package br.com.android.financas.activities;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.adapter.RecorrenteListaAdapter;
import br.com.android.financas.model.Despesa;
import br.com.android.financas.model.Recorrente;
import br.com.android.financas.repositorio.RepositorioDespesa;
import br.com.android.financas.repositorio.RepositorioRecorrente;
import br.com.android.financas.repositorio.impl.RepositorioDespesaImpl;
import br.com.android.financas.repositorio.impl.RepositorioRecorrenteImpl;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.ActionMode;

public class ListaRecorrente extends SherlockActivity {
	private ActionMode mMode;
	private ListView listaRecorrentes;
	private Recorrente recorrente;
	private RepositorioRecorrente repositorioRecorrente;
	private Activity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Sherlock___Theme_Light);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista_recorrente);
		activity = this;
		getSupportActionBar().setSubtitle(R.string.recorrente_subtile);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		try {
			repositorioRecorrente = new RepositorioRecorrenteImpl(this);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		listaRecorrentes = (ListView) findViewById(R.listaRecorrente.lista_recorrente);

		listaRecorrentes
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> adapterView,
							View view, int i, long l) {
						Recorrente recorrente = (Recorrente) listaRecorrentes
								.getAdapter().getItem(i);
						HomeRecorrente.callMe(ListaRecorrente.this,
								(Integer) recorrente.getId());
					}
				});

		listaRecorrentes
				.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View view, int i, long l) {
						recorrente = (Recorrente) listaRecorrentes.getAdapter()
								.getItem(i);

						mMode = startActionMode(new AnActionModeOfEpicProportions());
						return true;
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			fillList();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private void fillList() throws SQLException {
		Log.i(ListaRecorrente.class.getName(), "Show list again");

		ArrayAdapter<Recorrente> arrayAdapter = new RecorrenteListaAdapter(
				this, R.layout.recorrente_item, repositorioRecorrente.listar());
		listaRecorrentes.setAdapter(arrayAdapter);
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.lista_recorrente, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.menu_add:
			intent = new Intent(this, HomeRecorrente.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private final class AnActionModeOfEpicProportions implements
			ActionMode.Callback {

		@Override
		public void onDestroyActionMode(ActionMode mode) {
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode,
				com.actionbarsherlock.view.Menu menu) {
			menu.add(R.string.apagar).setIcon(R.drawable.trash)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode,
				com.actionbarsherlock.view.Menu menu) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode,
				final com.actionbarsherlock.view.MenuItem item) {
			// Toast.makeText(getActivity(),"Got click: " + item + " - " +
			// despesa.getDescricao(), Toast.LENGTH_SHORT).show();

			AlertDialog.Builder builder = new AlertDialog.Builder(activity);

			LayoutInflater factory = LayoutInflater.from(activity);
			View layout = factory.inflate(R.layout.apagar_despesa, null);
			final CheckBox todas = (CheckBox) layout
					.findViewById(R.apagar.todasGrupo);
			final CheckBox frente = (CheckBox) layout
					.findViewById(R.apagar.paraFrente);

			todas.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					if (check) {
						frente.setVisibility(View.INVISIBLE);
					} else
						frente.setVisibility(View.VISIBLE);
				}
			});

			builder.setView(layout);
			builder.setTitle(R.string.apagar_movimentacoes);

			frente.setText(R.string.apagar_apartir_meses);
			todas.setText(R.string.apagar_movimentacoes);

			builder.setCancelable(false);
			builder.setPositiveButton(R.string.sim,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// Toast.makeText(getActivity(),"Got click: " + item
							// + " - " + despesa.getDescricao(),
							// Toast.LENGTH_SHORT).show();
							try {
								RepositorioDespesa repositorioDespesa = new RepositorioDespesaImpl(
										activity);

								List<Despesa> despesas = new ArrayList<Despesa>();
								if (todas.isChecked()) {
									despesas = repositorioDespesa
											.getRecorrentes(recorrente);
								} else if (frente.isChecked()) {
									despesas = repositorioDespesa
											.getRecorrentes(recorrente,
													new Date());
								}

								repositorioDespesa.excluir(despesas);
								repositorioRecorrente.excluir(recorrente);
								fillList();
								Toast.makeText(activity,
										R.string.excluidos_sucesso,
										Toast.LENGTH_LONG).show();

							} catch (SQLException e) {
								e.printStackTrace();
							}

						}
					});
			builder.setNegativeButton(R.string.nao,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();

			mode.finish();
			return true;
		}
	}
}
